package com.attendancesystem.controller;

import com.attendancesystem.service.LectureService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.*;



import javax.servlet.annotation.WebServlet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(value = "/DeleteLectureController",name = "DeleteLectureController")
public class DeleteLectureController extends HttpServlet {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse rep) throws ServletException, IOException {
       req.setCharacterEncoding("UTF-8");
//        String lectureId = req.getParameter("lectureId");
        rep.setContentType("application/json;charset=UTF-8"); // 增加字符集定义
        PrintWriter out = rep.getWriter();
        ObjectNode json = objectMapper.createObjectNode();
//        System.out.println("lectureId:"+lectureId);
        try {
            JsonNode rootNode = objectMapper.readTree(req.getReader());
            String lectureId= rootNode.get("lectureId").asText();
            LectureService lectureService = new LectureService();
            json.put("success", true)
                    .put("message", "删除成功");
            out.print(json);
            lectureService.deleteLecture(lectureId);
        } catch (SQLException e) {
            rep.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            json.put("success", false)
                    .put("error", "数据库错误: " + e.getMessage());
            out.print(json);
        }catch (Exception e) {
            // 其他异常处理
            rep.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            json.put("success", false)
                    .put("error", "请求解析失败: " + e.getMessage());
            out.print(json);
        } finally {
            out.flush();
            out.close();
        }

    }
}
